import serial
import serial.tools.list_ports

class SerialComm:
    def __init__(self):
        self.ser = None

    def list_ports(self):
        return [port.device for port in serial.tools.list_ports.comports()]

    def open(self, port, baudrate=9600, timeout=1):
        self.ser = serial.Serial(port, baudrate, timeout=timeout)

    def close(self):
        if self.ser and self.ser.is_open:
            self.ser.close()

    def send(self, data: bytes):
        if self.ser and self.ser.is_open:
            print(f"[串口下行] {data.hex(' ').upper()}")
            self.ser.write(data)

    def receive(self, size=16):
        if self.ser and self.ser.is_open:
            data = self.ser.read(size)
            if data:
                print(f"[串口上行] {data.hex(' ').upper()}")
            return data
        return b''

    def is_open(self):
        return self.ser and self.ser.is_open 